import axios from 'axios';
import { useAuthStore } from '@/stores/auth';
import config from '@/config/config';
import router from '@/router/index';

const instance = axios.create({
  baseURL: `${config.getServerUrl()}/api`,
  timeout: 0,
});

instance.interceptors.request.use(
  config => {
    const authStore = useAuthStore();
    if (authStore.accessToken) {
      config.headers['Authorization'] = `Bearer ${authStore.accessToken}`;
    }
    return config;
  },
  error => Promise.reject(error)
);

instance.interceptors.response.use(
  response => response,
  async error => {
    if (error.response.status === 401) {
      const authStore = useAuthStore();
      try {
        await authStore.refreshAccessToken();
        return instance(error.config);
      } catch (refreshError) {
        router.push("/login");
        return Promise.reject(refreshError);
      }
    }

    return Promise.reject(error);
  }
);

export default instance;
